<template>
    <div class="p-2">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
            :leave-active-class="proxy?.animate.searchAnimate.leave">
            <searchrevealing>
                <el-tabs v-model="activeTab">
                    <el-tab-pane label="供应商管理" name="contract">
                        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="120px">
                            <el-form-item label="供应商名称" prop="supplierName">
                                <el-input style="width: 220px" v-model="queryParams.supplierName" placeholder="请输入供应商名称"
                                    maxlength="20" @keyup.enter="handleQuery"></el-input>
                            </el-form-item>
                            <el-form-item label="供应商类型" prop="supplierType">
                                <el-select style="width: 220px" v-model="queryParams.supplierType" placeholder="请选择"
                                    filterable clearable>
                                    <el-option v-for="dict in hm_supplier_type" :key="dict.dictValue"
                                        :label="dict.dictLabel" :value="dict.dictValue" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否已签合同" prop="sellStatus">
                                <el-select style="width: 220px" v-model="queryParams.sellStatus" placeholder="请选择"
                                    filterable clearable>
                                    <el-option v-for="dict in contractStatusList" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="是否大品牌免签" prop="bigBrandStatus">
                                <el-select style="width: 220px" v-model="queryParams.bigBrandStatus" placeholder="请选择"
                                    filterable clearable>
                                    <el-option v-for="dict in contractStatusList" :key="dict.value" :label="dict.label"
                                        :value="dict.value" />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                                <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </searchrevealing>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">
                    <!-- <el-col :span="1.5">
                        <el-button type="primary" @click="addSupplier">新增供应商</el-button>
                    </el-col> -->
                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'招商供应商管理'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="contractList" border @header-dragend="dragEnd">
                <el-table-column v-for="(item, index) in supplierColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <span v-if="item.prop == 'recruiterDepts'">
                            {{ handleExtraData(scope.row.extraData, 'recruiterDeptName') }}
                        </span>
                        <span v-if="item.prop == 'recruiters'">
                            {{ handleExtraData(scope.row.extraData, 'recruiterName') }}
                        </span>
                        <div v-if="item.prop == 'bigBrandStatus'">
                            <el-switch :model-value="scope.row.bigBrandStatus" size="small" :active-value="1"
                                :inactive-value="0"
                                @change="(e: boolean | string | number) => { handleBigBrandStatusChange(e, scope.row) }" />
                        </div>
                        <span v-if="item.prop == 'parentName'">
                            {{ handleExtraData(scope.row.extraData, 'parentName') }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150"
                    fixed="right">
                    <template #default="scope">
                        <div class="operation">
                            <el-button link type="primary" @click="handleDetails(scope.row)" class="color_theme">
                                详情</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>
    </div>
</template>

<script setup name="BigBrand" lang="ts">
import { ContractQueryParams, ContractTable } from '@/api/group/contract/types'
import { listHmContract, editBigBrandStatus } from '@/api/system/hmContract';
import { getDicts } from '@/api/system/dict/data/index'
import { listColumn } from '@/api/system/column';
import { ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance() as any;
const supplierColumns = ref()
const columnData = ref()

const queryFormRef = ref<ElFormInstance>();
const showSearch = ref(true);
const activeTab = ref('contract');
const loading = ref(true);
const total = ref(0);
const contractList = ref<ContractTable[]>([]);
const hm_supplier_type = ref()
const queryLoading = ref(false)
const contractStatusList = ref([
    { label: '是', value: '1' },
    { label: '否', value: '0' },
])
const router = useRouter();

const queryParams = reactive<ContractQueryParams>({
    pageNum: 1,
    pageSize: 10,
    supplierName: undefined,
    recruiterDept: undefined,
    recruiter: undefined,
    sellStatus: undefined,
    supplierType: undefined,
    bigBrandStatus: undefined
})

/** 根据合同类型获取合同名称 */
const contractNameByType = async (type: string, row: any) => {
    if (row) {
        const rows = row.filter((item: any) =>
            item.contractType == type
        )
        if (rows.length > 0) {
            return rows[0].fileName
        } else {
            return ''
        }
    } else {
        return ''
    }
}
/** 获取供应商类型字典 */
const getDictsList = async () => {
    const res = await getDicts('hm_supplier_type')
    hm_supplier_type.value = res.data
}

/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};
/** 招商部招商员多个回显 */
const handleExtraData = (data: any, recruiterDeptName: string) => {
    if (data) {
        const list: any[] = [];
        data.forEach((element: any) => {
            list.push(element[recruiterDeptName]);
        });
        return list.join(",");
    }
};
/** 查看详情 */
const handleDetails = async (row: ContractTable) => {
    router.push({
        path: '/suppliers/contractDetail',
        query: {
            supplierId: row.id,
            routerType: 'look',
            type: 'bigBrand'
        }
    })
}

const handleBigBrandStatusChange = async (val: boolean | string | number, row: any) => {
    ElMessageBox.confirm(`${val === 1 ? '是否将此供应商标记为大品牌免签' : '是否取消此供应商大品牌免签的标记'}`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        callback: async (action: any) => {
            if (action == 'confirm') {
                loading.value = true
                try {
                    const res = await editBigBrandStatus({ id: row.id, bigBrandStatus: val })
                    await getList()
                    ElMessage({
                        message: '修改完成',
                        type: 'success',
                    })
                    loading.value = false
                } catch (error) {
                    loading.value = false
                }
            }
        },
    })

}

/** 合同列表 */
const getList = async () => {
    try {
        loading.value = true;
        const res = await listHmContract(queryParams);
        const updatedRows = await Promise.all(res.rows.map(async (row: ContractTable) => {
            // 为每个合同类型调用contractNameByType并获取合同名称  
            const contractSellName = await contractNameByType('供销合同', row.contractList);
            const contractDiscountName = await contractNameByType('破价合同', row.contractList);
            const marginName = await contractNameByType('保证金协议', row.contractList);
            const supplementary = await contractNameByType('补充协议', row.contractList);
            const packageStatus = await contractNameByType('包销合同', row.contractList);
            row.contractSellName = contractSellName;
            row.contractDiscountName = contractDiscountName;
            row.marginName = marginName;
            row.supplementary = supplementary;
            row.packageStatus = packageStatus;
            return row;
        }));
        contractList.value = updatedRows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.pageSize)
    getColmun()
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('大品牌免签列表')
    supplierColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.pageSize)
}
onMounted(async () => {
    queryParams.pageNum = 1;
    await getColmun();
    await getList();
    getDictsList();
});
</script>
<style lang="scss" scoped>
.operation {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: center;
}

.el-dropdown {
    font-size: 14px !important;
}
</style>